<template>
  <div class="container">
      <toolsformap @selectmapimg="selectMapOrImg"></toolsformap>
      <measuretools :mapsformeasure="maps" @measureclick="measureclick"></measuretools>
    <div id="oneMap" class="map-container">
    </div>
  </div>
</template>

<script>
    import measuretools from "./components/measuretools";
    import toolsformap from "./components/toolsformap"
  import timeline from './components/timeline';
  import landarrtibute from "./components/landarrtibute";
  import manylayerattribute from "./components/manylayerattribute";
  import analysisform from "./components/analysisform";
  import Map from 'ol/Map.js';
  import View from 'ol/View.js';
  import {FullScreen,ScaleLine, defaults as defaultControls} from 'ol/control';
  import {Group as LayerGroup} from 'ol/layer';
  import Draw from 'ol/interaction/Draw';
  import Feature from 'ol/Feature';
  import VectorSource from 'ol/source/Vector';
  import {Vector as VectorLayer} from 'ol/layer';
  import {Icon, Style,Text,Circle as CircleStyle} from 'ol/style';
  import GeoJSON from 'ol/format/GeoJSON';
  import {WFS} from 'ol/format';
  import {Fill, Stroke} from 'ol/style';
  import Projection from "ol/proj/Projection";
  import {defaults} from 'ol/control.js';
  import {getWidth, getTopLeft} from 'ol/extent.js';
  import TileLayer from 'ol/layer/Tile.js';
  import TileWMS from 'ol/source/TileWMS';
  import TileGrid from "ol/tilegrid/TileGrid";
  import Tile from "ol/layer/Tile";
  import WMTS from 'ol/source/WMTS.js';
  import WMTSTileGrid from 'ol/tilegrid/WMTS.js';
  import MousePosition from 'ol/control/MousePosition';
  import {createStringXY} from 'ol/coordinate';
  import PluggableMap from 'ol/PluggableMap';
  import {getVectorContext} from 'ol/render';
  import {sortFeature} from "../../utils/map/countFeaturestype";
  import {getLayerStyle} from "../../api/cydtRequest";
  import XYZ from "ol/source/XYZ"
  import {get as getProjection} from 'ol/proj';
  import MultiPolygon from 'ol/geom/MultiPolygon'
  import ImageWMS from 'ol/source/ImageWMS';
  import {Image as ImageLayer} from 'ol/layer';
  import {
    and as andFilter,
    equalTo as equalToFilter,
    like as likeFilter,
    intersects as intersectsFilter,
    or as orFilter
  } from 'ol/format/filter';
  import axios from "axios";
  import bus from "../../assets/js/eventBus"
  import { register } from 'ol/proj/proj4';
  import proj4 from 'proj4';
  proj4.defs("EPSG:4490", "+proj=longlat +ellps=GRS80 +no_defs");
  register(proj4);
  PluggableMap.prototype.getEventPixel = function (event) {
    const viewportPosition = this.viewport_.getBoundingClientRect();
    let size = [viewportPosition.width, viewportPosition.height];
    const view = this.getView();
    if (view) {
      size = view.getViewportSize_();
    }
    const eventPosition =
            //FIXME Are we really calling this with a TouchEvent anywhere?
            'changedTouches' in event
                    ? /** @type {TouchEvent} */ (event).changedTouches[0]
                    : /** @type {MouseEvent} */ (event);
    return [
      ((eventPosition.clientX - viewportPosition.left) * size[0]) /
      viewportPosition.width,
      ((eventPosition.clientY - viewportPosition.top) * size[1]) /
      viewportPosition.height
    ];
  };
  export default {
    name: "oneMap",
    components: {
      manylayerattribute,
        toolsformap,
        measuretools
    },
    props:['changepage'],
    data(){
      return{
          legendinfo:{

          },
          legendinfoname:'',
          legendinfofilter:false,
        dialogTableVisible: false,
        dialogFormVisible: false,
          selectlayer:null,
          //secondlayer:null,
          fullscreenLoading: false,
        formLabelWidth: '80px',
        legendlayer:'',
        cliplayers:null,
        //retgeoinfo:[],
        drawgeom:null,
        drawstatus:false,
        //onelandarrtibutes:null,
        pagebtn:null,
        vectorlayer:null,
        //focusprojshow:false,
        closetree:true,
        newlayer:null,
        maps:null,
        layersarry:[],
        propertiesarry:[],
        type:"",
          basemaplayer:'',
          basezjlayer:'',
        mapInfoLayer:null,
        vectorSource:null,
        filterText: '',
        drawlayers:null,
        mapdraw:null,
        //showattribute:false,
        //layerCheckAdd,layerCheckDel用于存储左侧目录树的图层
        layerCheckAdd:[],
        layerCheckDel:[],
      }
    },
    created(){

    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      },
      changepage(newV,oldV){
        console.log(newV)
        this.closetree=newV.sta
        var geojsonObject={}
        if(newV.btnum==1){
        }
        if(newV.btnum==2){
        }
        if(newV.btnum==0){
        }
      },
    },
    mounted() {
      let that=this
      that.initMap()
      bus.$on("send", (data) => {
        this.layerCheckAdd = data[0];
        this.layerCheckDel = data[1];
        this.setlayer();
      });
      bus.$on("refresh", (data) => {
          this.refreshmap();
      });

    },
    methods:{
        measureclick(data){
            if(data.status){
               this.drawstatus=true
            }else {
                this.drawstatus=false
            }
        },
        getlayerstyles(layernamech){
            var that=this
            getLayerStyle({layername:layernamech}).then(res=>{
                that.legendinfo=res.data
            })
        },
        setlegendstyle(rgb){
            return { "background-color": rgb};
        },
        selectstyleshow(val){
            var sqlfilter="1=1"

            //控制性详细规划
            if(this.legendlayer=='xf:wj_konggui2022'){
                sqlfilter= "YDDM like '%"+val+"%'"

            }
            //建设用地管制区
            if(this.legendlayer=='xf:wj_jsydgzq2022'){
                sqlfilter= "GZQLXDM like '%"+val+"%'"

            }
            //2022重大项目
            if(this.legendlayer=='xf:zdxm2022'){
                sqlfilter= "LB like '%"+val+"%'"

            }
            //常州市总体规划
            if(this.legendlayer=='xf:czsztgh2011_2020'){
                sqlfilter= "MARK like '%"+val+"%'"

            }
            //基期地类
            if(this.legendlayer=='xf:wj_jqdl2022'){
                sqlfilter= "DLMC like '%"+val+"%'"

            }
            //土地用途区
            if(this.legendlayer=='xf:wj_tdytq2022'){
                sqlfilter= "TDYTQLXDM like '%"+val+"%'"

            }
            //武进村庄规划
            if(this.legendlayer=='xf:wjczgh2018_2020'){
                sqlfilter= "YDXZ like '%"+val+"%'"

            }
            //武进连片开发
            if(this.legendlayer=='xf:wjlpkf2022'){
                sqlfilter= "SSBK like '%"+val+"%'"

            }
            //现状用地分布
            if(this.legendlayer=='xf:wjxzydfb2022'){
                sqlfilter= "YJDL like '%"+val+"%'"

            }
            //5张产业名片
            if(this.legendlayer=='xf:wj95x52022'){
                sqlfilter= "cylb like '%"+val+"%'"

            }
            //9大重点产业
            if(this.legendlayer=='xf:wj95x92022'){
                sqlfilter= "cylb like '%"+val+"%'"

            }

            if(this.legendinfoname==val &&  this.legendinfofilter){
                sqlfilter="1=1"
                this.legendinfofilter=!this.legendinfofilter

            }else{
                this.legendinfofilter=!this.legendinfofilter
                this.legendinfoname=val
            }
            var sellayername=this.legendlayer
            let params={
                LAYERS: sellayername,
                CQL_FILTER: sqlfilter
            }
            this.newlayer.getSource().updateParams(params)
        },
      drawinfo(){
        var that=this
        this.drawstatus=true
        if(this.drawlayers!=null){
            this.mapdraw.setActive(true)
          return
        }
        const source = new VectorSource({wrapX: false});
        const vector = new VectorLayer({
          source: source,
          zIndex:9999
        });
        this.drawlayers=vector
        this.maps.addLayer(vector)
         var draw; // global so we can remove it later
          const value = 'Polygon';
          if (value !== 'None') {
             draw = new Draw({
              source: source,
              type: value,
            });

            this.mapdraw=draw
            this.maps.addInteraction(draw);
            draw.on('drawend',function (e) {
              that.drawgeom=e.feature.getGeometry()
                draw.setActive(false)

              // vector.getSource().on('addfeature', function () {
              //   that.dtlayer.setExtent(vector.getSource().getExtent());
              // });
            })
          }
      },
        openFullScreen(val) {
            const loading = this.$loading({
                lock: true,
                text: 'Loading',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
            });
            setTimeout(() => {
                loading.close();
            }, 2000);

    },
      addVectorlayer(geojsonObject){
        if(this.vectorlayer!=null){
          this.maps.removeLayer(this.vectorlayer)
        }
        const styles = {
          'MultiPolygon': new Style({
            stroke: new Stroke({
              color: 'red',
              width: 2,
              lineDash:[20]
            }),
            fill: new Fill({
              color: 'rgba(255, 255, 0, 0.5)',
            }),
            text: new Text({
              font: '20px Microsoft YaHei',
              text:  geojsonObject.features[0].properties.kid,
              fill: new Fill({
                color: '#000'
              })
            })
          }),
          'Polygon': new Style({
            stroke: new Stroke({
              color: 'red',
              lineDash: [4],
              width: 3,
            }),
            fill: new Fill({
              color: 'rgba(0, 0, 255, 0.1)',
            }),
          }),
            'Point': new Style({
                fill: new Fill({
                    color: 'rgba(255, 255, 255, 0.2)',
                }),
                stroke: new Stroke({
                    color: 'rgba(0, 0, 0, 0.5)',
                    lineDash: [10, 10],
                    width: 2,
                }),
                image: new CircleStyle({
                    radius: 20,
                    stroke: new Stroke({
                        color: 'rgba(255, 0, 0, 0.7)',
                    }),
                    fill: new Fill({
                        color: 'rgba(255, 0, 0, 0.2)',
                    }),
                }),

            })
        };
        const vectorSource = new VectorSource({
          features: new GeoJSON().readFeatures(geojsonObject),
        });
        const styleFunction = function (feature) {
          return styles[feature.getGeometry().getType()];
        };
        const vectorLayer = new VectorLayer({
          source: vectorSource,
          style: styleFunction,
        });
        this.maps.addLayer(vectorLayer)
        const feature = vectorSource.getFeatures()[0];
        const polygon = feature.getGeometry();
        this.maps.getView().fit(polygon,{maxZoom:15})
        this.vectorlayer=vectorLayer
      },
      getlayersource(url,layername){
        console.log(url);
          console.log(layername);
          var layers = new ImageLayer({
              source: new ImageWMS({
                  //不能设置为0，否则地图不展示。
                  ratio: 1,
                  url: url,
                  params: {
                      LAYERS: layername,
                      VERSION: "1.1.0",
                      FORMAT: "image/png",
                      STYLES: "",
                  },
                  serverType: "geoserver",
              }),
          });

        this.newlayer=layers;

        return layers;
      },
      setlayer(){
        var that=this
        console.log('开始加载');
        if(this.layerCheckDel){
          for(let i=0;i<this.layerCheckDel.length;i++){
            for(let j=0;j<that.layersarry.length;j++){
              if(that.layersarry[j].id===this.layerCheckDel[i].id){
                that.maps.removeLayer(that.layersarry[j].layer)
                that.layersarry.splice(j,1)
                break;
              }
            }
          }
        }
        if(this.layerCheckAdd){
          for(let i=0;i<this.layerCheckAdd.length;i++){
            const layer=that.getlayersource(this.layerCheckAdd[i].serverurl,this.layerCheckAdd[i].layername)
            that.layersarry.push({'id':this.layerCheckAdd[i].id,'layer':layer,'layername':this.layerCheckAdd[i].label})
            that.legendlayer=this.layerCheckAdd[i].layername
            //that.getlayerstyles(this.layerCheckAdd[i].label)
            that.maps.addLayer(layer)
          }
        }

      },
      refreshmap(){
          var that=this;
          let x=that.maps.getView().getCenter()[0]+1;
          let y=that.maps.getView().getCenter()[1];
          console.log("x:"+x)
          that.maps.getView().setCenter([x,y]);
      },


      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      getlayerinfo(layerID,layer,evt){
        var that=this
        var view=that.maps.getView()
        var viewResolution = view.getResolution();
        var propertiesformany={}
        var source =  layer.layer.get('visible') ? layer.layer.getSource():that.newlayer.getSource();
        var url = source.getFeatureInfoUrl(
                evt.coordinate, viewResolution, view.getProjection(),
                {'INFO_FORMAT': 'application/json', 'FEATURE_COUNT': 50})
        if (url) {
          console.log(url)
            //本地跨域问题修改url打包服务器应注意
          axios.get(url)
                  .then(response => {
                    if(response.data.features){
                      for(var i=0;i<response.data.features.length;i++){
                        propertiesformany=Object.assign(propertiesformany,response.data.features[i].properties)
                      }

                      //that.showattribute=true
                      that.addVectorlayer(response.data)
                    }else{
                      //that.showattribute=false
                    }
                  })
                  .catch(error => {
                    console.log(error)
                  })
                  .finally(()=>{
                    that.propertiesarry.push({'layerid':layerID,'layername':layer.layername,'properties':propertiesformany})
                  }
                  )
        }
      },
      initMap() {
        var that=this
        console.log("开始加载地图！");
          //对应源代码中的全图范围信息
          var fullExtent = [34876800.0,3434652.7368686665,40545132.45925026,10002100.0];
          var projection = new Projection({
              code: 'EPSG:4528',
              units: 'm',
              axisOrientation: 'neu',
              global: false
          });
          var dtlayer=that.getDtTileSLayer('dzdt')
          that.basemaplayer=dtlayer

          var map = new Map({
          layers: [
              dtlayer
          ],
          target: 'oneMap',
          view: new View({
              projection: projection,
              center: [40490897.633, 3497008.407],
              //resolutions: resolutions,
              resolution: 79.37515875031751,
              extent: fullExtent
           }),
          });
          //that.basemaplayer=tileLayerDZDT;
        that.maps=map
          //记得问一下这行代码的功能20221204WGC
        //map.getView().fit([34876800.0,3434652.7368686665,40545132.45925026,10002100.0], map.getSize());
        this.$store.state.map=map
        map.on('singleclick', function(evt){
          if(that.drawstatus){return}
          // console.log(map.getLayerGroup())
          var view = map.getView();
          var viewResolution = view.getResolution();
          const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
            return feature;
          });
          if(feature){
            if(that.pagebtn==1){

              //that.showoneattribute=true
            }
            if(that.pagebtn==2){
              //that.focusprojshow=true
            }
          }else{
            /*that.showoneattribute=false
            that.focusprojshow=false
            that.showattribute=false*/
            that.maps.removeLayer(that.vectorlayer)
          }

          if(that.layersarry.length>0){
              console.log("hhhhhhhhh")
              that.propertiesarry=[];
            for(let i=0;i<that.layersarry.length;i++){
              that.getlayerinfo(i,that.layersarry[i],evt)
            }
            //向myMap-right传递属性数据
              console.log("heeees11")
            var propertieItems=that.propertiesarry;

            console.log(propertieItems)
            bus.$emit("propertieItems", propertieItems);
          }else{
            //that.showattribute=false
           // that.maps.removeLayer(that.vectorlayer)
          }

        })
      },
        //数组排序
        sortByKey(propertyName) {
            return function(object1, object2) {
                var value1 = object1[propertyName];
                var value2 = object2[propertyName];
                if(value2 < value1) {
                    return -1;
                } else if(value2 > value1) {
                    return 1;
                } else {
                    return 0;
                }
            }
        },
        maopao(arr,propertyName){
        for(let i=0;i<arr.length-1;i++){
            for(let j=i;j<arr.length;j++){
                if(arr[i]>arr[j]){
                    let changeData = arr[i]
                    arr[i] = arr[j]
                    arr[j] = changeData
                }
            }
        }
        return arr
    },


        //获取底图Tiles 20221204WGC
        getDtTileSLayer(category){
            var projection = new Projection({
                code: 'EPSG:4528',
                units: 'm',
                axisOrientation: 'neu',
                global: false
            });
            projection.setExtent([34876800.0,3434652.7368686665,40545132.45925026,10002100.0]);
            projection.setWorldExtent([34876800.0,3434652.7368686665,40545132.45925026,10002100.0]);
            const projectionExtent = projection.getExtent();

            //对应源代码中的源信息
            var origin = [34876800.0, 10002100.0]
            //对应源代码中的全图范围信息
            var fullExtent = [34876800.0,3434652.7368686665,40545132.45925026,10002100.0]
            //对应源代码中的切片方案信息
            var resolutionsDZDT = [152.7029218548022, 76.3514609274011, 38.17573046370042, 19.087865231850262, 9.543932615925145, 4.771966307962573, 2.3859831539812832, 1.1929915769906416, 0.5964957884953221, 0.29824789424766107, 0.14912394712383054]
            var tileGridDZDT = new TileGrid({
                tileSize: 256,
                origin: origin,
                extent: fullExtent,
                resolutions: resolutionsDZDT
            });
            var resolutionsYXDT = [132.2919312505292, 79.37515875031751, 39.687579375158755, 26.458386250105836, 13.229193125052918, 5.291677250021167, 2.6458386250105836, 1.3229193125052918, 0.5291677250021167, 0.26458386250105836]
            var tileGridYXDT = new TileGrid({
                tileSize: 256,
                origin: origin,
                extent: fullExtent,
                resolutions: resolutionsYXDT
            });

            var tileLayerDZDT = new Tile({
                source: new TileWMS({
                    url: "http://localhost:8080/geowebcache/service/wms",
                    params: {
                        LAYERS: "WJ_DZDT",
                        VERSION: "1.1.1",
                        FORMAT: "image/jpeg",
                        //SRS:'EPSG:4528'
                    },
                    tileGrid: tileGridDZDT
                }),
            });

            var tileLayerYXDT = new Tile({
                source: new TileWMS({
                    url: "http://localhost:8080/geowebcache/service/wms",
                    params: {
                        LAYERS: "WJ_YXDT",
                        VERSION: "1.1.1",
                        FORMAT: "image/jpeg",
                        //SRS:'EPSG:4528'
                    },
                    tileGrid: tileGridYXDT
                }),
            });

            var dtlayer = tileLayerDZDT;
            if(category==='yxdt'){
                dtlayer = tileLayerYXDT;
            }

            return dtlayer;

        },
        //加载本地电子地图和影像20221204WGC
        addbaseimglayer(val){
            var basemaplayer1=null
            var layersArray = this.maps.getLayers();
            if(val==='电子影像'){
                this.maps.removeLayer(this.basemaplayer)
                 basemaplayer1= this.getDtTileSLayer('yxdt');
                this.basemaplayer=basemaplayer1
                layersArray.insertAt(0,basemaplayer1);
            }
            if(val==='电子地图'){
                this.maps.removeLayer(this.basemaplayer)
                basemaplayer1= this.getDtTileSLayer('dzdt');
                this.basemaplayer=basemaplayer1;
                layersArray.insertAt(0,basemaplayer1);
            }


        },
        selectMapOrImg(val){
         this.addbaseimglayer(val)
        },
      cliplayeradd(e){
        var that=this
        if(that.cliplayers!=null){
          that.maps.removeLayer(that.cliplayers)
        }
        const cliplayer=this.getlayersource(e.serverurl,e.layername)
        const style = new Style({
          fill: new Fill({
            // color:'transparent',
            strokeStyle:'red',
          }),
        });
        cliplayer.on('prerender', function (e) {
           cliplayer.setExtent(that.drawgeom.getExtent());
          const vectorContext = getVectorContext(e);
          // e.context.globalCompositeOperation = 'destination-in';
          let ctx = e.context;
          ctx.save();
          that.drawlayers.getSource().forEachFeature(function (feature) {
            vectorContext.drawFeature(feature, style);
          });
          e.context.globalCompositeOperation = 'source-over';
          ctx.clip();
        });
        cliplayer.on('postrender', function (e) {
          let ctx = e.context;
          ctx.restore();
        })
        this.maps.addLayer(cliplayer)
        that.cliplayers=cliplayer
      },


    }
  }
</script>

<style >
  @import 'myMap.scss';
</style>
